package com.learn.consumer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/08/16
 * @description ch01 hello_world 消费者 and 工作队列的消费者
 */
public class Consumer {
    public static final String QUEUE_NAME = "hello_world";

    public static void main(String[] args) throws Exception {
        // 创建连接工厂，设置属性
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");
        // 创建连接
        Connection connection = factory.newConnection();
        // 获取信道
        Channel channel = connection.createChannel();

        /*
        消费消息，参数：
        1. 队列名称
        2. 是否自动答应, 接收到消息就自动返回ack，并删除
        3. DeliverCallback 消息成功时回调方法
        4. CancelCallback 消息失败时回调
         */
        channel.basicConsume(QUEUE_NAME, true, (consumerTag, message) -> {
            System.out.println(message.toString());
            System.out.println(new String(message.getBody()));
        }, (consumerTag) -> {
            System.out.println(consumerTag);
        });
    }
}
